package com.run2code.design.behavioral.memento;

/**
 * 文本编辑器（发起人）
 * 关注公众号【奔跑的码畜】，一起进步不迷路
 *
 * @author 第七人格
 * @date 2024/06/12
 */
class TextEditor {
    /**
     * 编辑器状态
     */
    private final TextEditorState state;
  
    public TextEditor(String initialText) {  
        this.state = new TextEditorState(initialText, 0);  
    }  
  
    public void setText(String text) {  
        this.state.setText(text);
    }  
  
    public void setCursorPosition(int position) {  
        this.state.setCursorPosition(position);
    }  
  
    public TextEditorMemento saveState() {
        // 注意：这里返回的是状态的一个拷贝，以防止外部修改影响内部状态
        return new TextEditorMemento(new TextEditorState(state.getText(), state.getCursorPosition()));
    }  
  
    public void restoreState(TextEditorMemento memento) {  
        TextEditorState savedState = memento.getState();  
        this.state.setText(savedState.getText());
        this.state.setCursorPosition(savedState.getCursorPosition());
    }  
  
    public String getText() {  
        return state.getText();
    }  
  
    public int getCursorPosition() {  
        return state.getCursorPosition();
    }  
}